<template>
  <view class="consultation-detail-page">
    <view class="page-header">
      <text class="page-title">问诊详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button v-if="consultation.status !== 2" class="btn btn-primary" @click="handleEdit">回复</button>
        <button class="btn btn-danger" @click="handleDelete">删除</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">问诊状态</text>
          <view :class="['status-badge', getStatusClass(consultation.status)]">
            {{ getStatusText(consultation.status) }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">患者ID</text>
            <text class="value">{{ consultation.patient_id || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">医生ID</text>
            <text class="value">{{ consultation.doctor_id || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(consultation.create_time) }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card conversation-card">
        <view class="card-header">
          <text class="card-title">问诊对话</text>
        </view>
        <view class="card-body">
          <view class="message-bubble question-bubble">
            <view class="message-header">
              <text class="message-author">患者提问</text>
              <text class="message-time">{{ formatTime(consultation.create_time) }}</text>
            </view>
            <view class="message-content">
              <text>{{ consultation.question || '-' }}</text>
            </view>
            <view v-if="consultation.attachments && consultation.attachments.length > 0" class="message-attachments">
              <text class="attachments-title">附件（{{ consultation.attachments.length }}个）</text>
              <view class="attachments-list">
                <view v-for="(file, index) in consultation.attachments" :key="index" class="attachment-item" @click="previewFile(file)">
                  <text class="attachment-icon">📎</text>
                  <text class="attachment-name">附件{{ index + 1 }}</text>
                </view>
              </view>
            </view>
          </view>

          <view v-if="consultation.answer" class="message-bubble answer-bubble">
            <view class="message-header">
              <text class="message-author">医生回复</text>
              <text class="message-time">{{ formatTime(consultation.answer_time) }}</text>
            </view>
            <view class="message-content">
              <text>{{ consultation.answer }}</text>
            </view>
          </view>

          <view v-else class="empty-answer">
            <text>医生暂未回复</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const loading = ref(true)
const consultationId = ref('')
const consultation = reactive({
  patient_id: '',
  doctor_id: '',
  question: '',
  attachments: [],
  answer: '',
  status: 0,
  create_time: null,
  answer_time: null,
  update_time: null
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  consultationId.value = currentPage.options.id || ''
  
  if (!consultationId.value) {
    uni.showToast({ title: '缺少问诊ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/consultations/list' })
    }, 1500)
    return
  }
  
  await loadConsultationData()
  loading.value = false
})

async function loadConsultationData() {
  try {
    // 调用云对象方法获取问诊信息
    const consultationsObj = uniCloud.importObject('dh-consultations')
    const result = await consultationsObj.getConsultationById(consultationId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(consultation, result.data)
    } else {
      throw new Error(result.message || '问诊记录不存在')
    }
  } catch (err) {
    console.error('加载问诊数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/consultations/list' })
    }, 1500)
  }
}

function getStatusText(status) {
  const statusMap = {
    0: '待回复',
    1: '已回复',
    2: '已结束'
  }
  return statusMap[status] || '未知'
}

function getStatusClass(status) {
  const classMap = {
    0: 'status-pending',
    1: 'status-answered',
    2: 'status-closed'
  }
  return classMap[status] || ''
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function previewFile(url) {
  // 简单预览，实际应根据文件类型判断
  uni.previewImage({
    urls: [url],
    current: url
  })
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/consultations/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/consultations/edit?id=${consultationId.value}` })
}

function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条问诊记录吗？此操作不可撤销。',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          // 调用云对象方法软删除咨询
          const consultationsObj = uniCloud.importObject('dh-consultations')
          const result = await consultationsObj.deleteConsultation(consultationId.value, '详情页删除')
          uni.hideLoading()
          if (result.code === 200) {
            uni.showToast({ title: result.message || '删除成功', icon: 'success' })
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'none' })
            return
          }
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/business/consultations/list' })
          }, 1500)
        } catch (err) {
          console.error('删除失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '删除失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.consultation-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .btn {
    flex: 1;
    min-width: 0;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-pending {
    background: #fff3e0;
    color: #e65100;
  }
  
  &.status-answered {
    background: #e8f5e9;
    color: #2e7d32;
  }
  
  &.status-closed {
    background: #e3f2fd;
    color: #1976d2;
  }
}

.card-body {
  padding: 32rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.conversation-card .card-body {
  padding: 20rpx;
  background: #f8f9fa;
}

.message-bubble {
  padding: 24rpx;
  border-radius: 12rpx;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.question-bubble {
  background: #e3f2fd;
  border-left: 4rpx solid #1976d2;
}

.answer-bubble {
  background: #e8f5e9;
  border-left: 4rpx solid #2e7d32;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.message-author {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.message-time {
  font-size: 24rpx;
  color: #999;
}

.message-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.message-attachments {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid rgba(0, 0, 0, 0.08);
}

.attachments-title {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 12rpx;
}

.attachments-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.attachment-item {
  padding: 12rpx 20rpx;
  background: #fff;
  border: 1rpx solid #e0e0e0;
  border-radius: 20rpx;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
  
  &:active {
    background: #f5f5f5;
  }
}

.attachment-icon {
  font-size: 28rpx;
}

.attachment-name {
  color: #333;
}

.empty-answer {
  padding: 80rpx 0;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}
</style>
